@<template>
  <div>
     <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
        <el-alert title="添加商品信息" type="info" center show-icon>
        </el-alert>

        <!-- 步骤条 -->
        <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <!-- tab标签 -->
        <el-form :model="addForm" ref="addFormRef" label-width="100px" 
        label-position="top" :rules="addFormRules">
            <el-tabs @tab-click="tabChange" :before-leave="beforeLeaveTab" v-model="activeIndex" :tab-position="'left'" >
                <el-tab-pane label="基本信息" name='0'>
                    <el-form-item label="商品名称" prop="goods_name" >
                        <el-input v-model="addForm.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品价格" prop="goods_price" >
                        <el-input v-model="addForm.goods_price"></el-input>
                    </el-form-item>
                    <el-form-item label="商品重量" prop="goods_weight" >
                        <el-input v-model="addForm.goods_weight"></el-input>
                    </el-form-item>
                    <el-form-item label="商品数量" prop="goods_number" >
                        <el-input v-model="addForm.goods_number"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" >
                        <el-cascader
                            v-model="addForm.goods_cat"
                            :options="cateList"
                            :props="cateProps"
                            @change="handleChange">
                        </el-cascader>
                    </el-form-item>
                   
                    
                </el-tab-pane>
                <el-tab-pane label="商品参数" name='1'>
                    <!-- 渲染动态参数表格区域 -->
                    <el-form-item v-for="item in manyGoodsData" :key="item.attr_id" 
                    :label="item.attr_name">
                        <!-- 复选框区域 -->
                          <el-checkbox-group v-model="item.attr_vals">
                            <el-checkbox border v-for="(name, i) in item.attr_vals" 
                            :key="i" :label="name"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name='2'>
                    <el-form-item :label="item.attr_name" v-for="item in onlyGoodsData" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name='3'>
                    <el-upload
                    :on-success="onSuccess"
                    :headers="headerObj"
                    :action="upLodaUrl"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name='4'>
                    <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                    <el-button type="primary" @click="add" class="add-goods">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
    title="图片预览"
    :visible.sync="imgDialogVisible"
    width="50%"
    >
    <img :src="imgView" alt="">

    </el-dialog>
  </div>
</template>

<script>
// 深度拷贝的包
import _ from 'lodash'
export default {

    data() {
        return {
            activeIndex: '0',
            addForm: {
                goods_name: '',
                goods_price: '',
                goods_weight: '',
                goods_number: '',
                // 商品所属的分类数组
                goods_cat: [],
                // 图片的数组
                pics: [],
                // 商品的详情描述
                goods_introduce: '',
                // 存放动态参数或静态属性对象
                attrs:[],
                
            },
            // 分类数据列表
            cateList: [],
            // 级联框配置对象
            cateProps: {
                expandTrigger: "hover",
                value: "cat_id",
                label: "cat_name",
                children: "children",

            },
            // 动态参数数据存放对象
            manyGoodsData: [],
            // 静态属性数据的存放对象
            onlyGoodsData: [],
            // 图片上传地址
            upLodaUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
            // 设置上传图片的请求头
            headerObj:{
                Authorization: window.sessionStorage.getItem('token')
            },
            // 图片预览地址
            imgView: '',
            // 图片预览对话框 隐藏或显示
            imgDialogVisible: false,
            addFormRules: {
                goods_name: [
                    {required: true, message: '请输入商品名称' ,trigger: 'blur'}
                ],
                goods_price: [
                    {required: true, message: '请输入商品价格' ,trigger: 'blur'}
                ],
                goods_weight: [
                    {required: true, message: '请输入商品重量' ,trigger: 'blur'}
                ],
                goods_number: [
                    {required: true, message: '请输入商品数量' ,trigger: 'blur'}
                ],
                goods_cate: [
                    {required: true, message: '请选择商品分类' ,trigger: 'blur'}
                ],
            }
        }
    },
    created(){
        this.getCateList()
    },
    methods: {
        // 请求分类列表
        async getCateList() {
            const {data: res} = await this.$http.get('categories')
            if(res.meta.status != 200) {
                return this.$message.error("获取分类列表失败")
            }
            this.cateList = res.data
           
        },
        // 级联选择框选择事件处理函数
        handleChange() {
            // 仅允许选择三级分类
            if(this.addForm.goods_cat.length != 3) {
                this.addForm.goods_cat = []
            }
        },
        // 标签页发生切换事件的处理函数
        beforeLeaveTab(newName, oldName) {
            if(oldName == 0 && this.addForm.goods_cat.length != 3) {
                this.$message.error("请先选择商品分类!")
                return false
            }
        },
         // tab标签切换事件
        tabChange() {
            console.log(this.activeIndex)
            // 证明为商品参数tab页
            if(this.activeIndex == 1) {
                //  发起请求参数
                this.getGoodsParam('many')
            }else if(this.activeIndex == 2) {
                // 发起获取静态属性请求
                this.getGoodsParam('only')
              
            }
        },
        // 获取商品参数
        async getGoodsParam(type) {
        //  发起请求参数
            const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                params: {sel: type}                   
            })

            if(res.meta.status != 200) {
                return this.$message.error("获取商品参数失败");
            }
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals.length == 0 ? 
                []: item.attr_vals.split(',')
            })

            if(type == "many"){

                this.manyGoodsData = res.data;
            }else if(type == "only"){
                res.data.forEach(item=> {
                    item.attr_vals = item.attr_vals.join(',')
                })
                this.onlyGoodsData = res.data;
                console.log(this.onlyGoodsData)

            }
        },
        // 图片预览处理函数
        handlePreview(file) {
            this.imgView = file.response.data.url
            this.imgDialogVisible = true

        },
        // 删除图片处理函数
        handleRemove(file) {
            // 1.获取将要删除的临时文件名
            const pathInfo = file.response.data.tmp_path
            //  2.查找对象在列表中的索引
            const index = this.addForm.pics.findIndex(item => {
                return item.pic == pathInfo
            })
            console.log(index)
            // 3. 使用spilce删除对象
            this.addForm.pics.splice(index, 1)
            this.$message.success("删除成功")
            console.log(this.addForm.pics)

        },
        // 上传成功后事件处理函数
        onSuccess(response) {
            // 拼接图片对象
            const pic = {'pic': response.data.tmp_path}
            // 将文件对象添加到图片列表
            this.addForm.pics.push(pic)
            console.log(this.addForm.pics)

        },
        // 添加商品的时间
        add() {
            // 表单预验证
            this.$refs.addFormRef.validate( async valid => {
                if(!valid) {
                    return this.$message.error("请选择必填的表单项")
                }
            // 添加商品的业务逻辑

            // 添加之前深度拷贝,因为级联选择框对应的是数组,
            // 而服务器端接收的是字符串goods_cat
                const form = _.cloneDeep(this.addForm)
                form.goods_cat = form.goods_cat.join(',')
                console.log(form)
                // 处理动态参数
                this.manyGoodsData.forEach(item => {
                    const manyInfo = {attr_id: item.attr_id, attr_value: item.attr_vals.join(',')}
                    this.addForm.attrs.push(manyInfo)
                })
                // 处理静态属性
                this.onlyGoodsData.forEach(item => {
                    const onlyInfo = {attr_id: item.attr_id, attr_value:item.attr_vals}
                    this.addForm.attrs.push(onlyInfo)
                })

                form.attrs = this.addForm.attrs;
                console.log(form)

                // 发送添加商品请求, 注意 商品名称必须唯一
                const {data: res} = await this.$http.post('goods', form)
                if(res.meta.status != 201) {
                    return this.$message.error("添加商品失败")
                }
                this.$message.success('商品添加成功')
                this.$router.push('/goods')
            })

            


        }
    },
    computed: {
        cateId() {
            if(this.addForm.goods_cat.length == 3) {
                return this.addForm.goods_cat[2]
            }
            return null
        }
    }
}
</script>

<style lang="less" scoped>
.el-checkbox {
    margin: 0 10px 0 0 !important;
}
.el-dialog img {
    width: 100%;
}
.add-goods {
    margin-top: 15px;
}
</style>